package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author An
 */
@Slf4j
@Service
@Transactional
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired
    private AdUserMapper adUserMapper;

    /**
     * 平台管理登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        // 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 判断用户是否正常登录
        if (StringUtils.isNotEmpty(dto.getName()) && StringUtils.isNotEmpty(dto.getPassword())) {
            // 根据账号查询用户
            AdUser adUser = adUserMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
            if (adUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            } else {
                // 获取salt
                String salt = adUser.getSalt();
                // 密码加密
                String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
                // 判断密码是否正确
                if (adUser.getPassword().equals(password)) {
                    // 校验通过,返回数据并携带token
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                    // 隐藏敏感数据
                    adUser.setPassword("");
                    adUser.setSalt("");
                    resultMap.put("user", adUser);

                    return ResponseResult.okResult(resultMap);
                } else {
                    // 返回密码不正确
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }
        }


        return null;
    }
}
